package org.example.handler;

import com.alibaba.fastjson.JSONObject;
import org.example.common.enums.ResultEnum;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录失败处理
 * 返回失败信息
 * 还可以自定义跳转到登录页面
 */
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.warn("Authentication does not pass");

        Map<String, Object> resMap = new HashMap<>();
//        resMap.put("msg", "Authentication does not pass");
        resMap.put("msg", exception.getMessage());
        resMap.put("code", ResultEnum.FailResult.getCode());

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSONObject.toJSONString(resMap));
        response.flushBuffer();
    }
}
